<template>
  <div class="category-tabs">
    <!-- 加载中 -->
    <el-skeleton v-if="loading" :rows="1" animated />

    <!-- 错误提示 -->
    <div v-else-if="error" class="error-message">
      {{ errorMessage }}
      <el-button type="text" @click="retry">点击重试</el-button>
    </div>

    <!-- 标签按钮 -->
    <div v-else>
      <el-button
        v-for="(tab, index) in tabs"
        :key="index"
        :class="{ active: activeTab === tab.value }"
        @click="handleTabClick(tab.value)"
        style="height: 45px;"
      >
        {{ tab.label }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { getBoardsByNum } from '@/api/boardApi'; // 假设你有该接口
import { useBoardStore } from '@/stores/boardStore';

const boardStore = useBoardStore();
const tabs = ref([]);
const activeTab = ref(null);
const loading = ref(true);
const error = ref(false);
const errorMessage = ref('');

// 自定义事件 emit
const emit = defineEmits(['update:activeTab']);

// 获取板块信息
const fetchCategories = async () => {
  loading.value = true;
  error.value = false;

  try {
    const res = await getBoardsByNum(10); // 假设这个接口返回的是你提供的数组

    if (Array.isArray(res) && res.length > 0) {
      tabs.value = res.map(item => ({
        label: item.name,   // 使用 name 作为显示文本
        value: item.id      // 使用 id 作为唯一标识符
      }));

      activeTab.value = tabs.value[0].value;
      emit('update:activeTab', activeTab.value);
    } else {
      throw new Error('数据为空或格式错误');
    }
  } catch (err) {
    error.value = true;
    errorMessage.value = err.message;
    console.error('获取分类失败:', err);
  } finally {
    loading.value = false;
  }
};

// 点击切换标签
const handleTabClick = (value) => {
  activeTab.value = value;
  boardStore.setActiveBoardId(value);
  emit('update:activeTab', value);
};

// 页面挂载时请求数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped>
.category-tabs {
  max-width: 1200px;  /*  设置最大宽度 */
  width: 100%;         /* 自适应 */
  margin: 0 auto;      /* 居中对齐 */
  display: flex;
  justify-content: center;
  gap: 10px;
  flex-wrap: wrap;
}

.category-tabs .el-button {
  background-color: #f5f5f5;
  color: #333;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 14px;
}

.category-tabs .el-button.active {
  background-color: #000;
  color: #fff;
}

.error-message {
  color: red;
  font-size: 14px;
  margin-left: 10px;
}
</style>